package com.dao;

import com.google.gson.Gson;
import com.model.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2017/3/2.
 */
@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private Gson gson = new Gson();

    /**
     * 用户登录认证
     *
     * @param userName
     * @param password
     * @return
     */
    public int getMatchCount(String userName, String password) {
        String sql = "SELECT COUNT(*) AS HasCount FROM t_users WHERE user_name='" + userName + "' AND pwd='" + password + "'";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql);
        Object count =map.get("HasCount");
        System.out.println(count);
        return Integer.parseInt(count.toString());
    }

    /**
     * 根据用户名称查找用户信息
     *
     * @param username
     * @return
     */
    public Users finUserByUserName(String username) {
        String sql = "SELECT user_id,user_name,credits,pwd, last_visit,last_ip FROM t_users WHERE user_name=?";
        Users users = new Users();
        jdbcTemplate.query(sql, new Object[]{username}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                users.setUser_id(resultSet.getInt("user_id"));
                users.setUser_name(resultSet.getString("user_name"));
                users.setCredits(resultSet.getInt("credits"));
                users.setPwd(resultSet.getString("pwd"));
                users.setLast_visit(resultSet.getDate("last_visit"));
                users.setLast_ip(resultSet.getString("last_ip"));
            }
        });
        return users;
    }

    /**
     * 更新用户信息
     *
     * @param users
     */
    public void updateUserInfo(Users users) {
        String sql = "UPDATE t_users set credits = ? ,last_visit = ? ,last_ip = ? WHERE user_id =?";
        jdbcTemplate.update(sql, new Object[]{users.getCredits(), users.getLast_visit(), users.getLast_ip(), users.getUser_id()});
    }
}
